package me.zhengjie.modules.system.rest

import me.zhengjie.common.exception.BadRequestException
import me.zhengjie.common.utils.*
import me.zhengjie.logging.annotation.Log
import me.zhengjie.modules.system.domain.*
import me.zhengjie.modules.system.service.JobService
import me.zhengjie.modules.system.service.dto.*

import io.swagger.v3.oas.annotations.media.Schema
import jakarta.servlet.http.HttpServletResponse
import org.springframework.data.domain.Pageable
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import java.io.IOException

/**
 * @author Kuki Wu
 * @date 2019-03-29
 */
@Schema(description = "系统：岗位管理")
@RestController
@RequestMapping("/api/job")
class JobController(private val jobService: JobService) {
    @Log("导出岗位数据")
    @Schema(description = "导出岗位数据")
    @GetMapping(value = ["/download"])
    @PreAuthorize("@el.check('job:list')")
    @Throws(
        IOException::class
    )
    fun download(response: HttpServletResponse?, criteria: JobQueryCriteria?) {
        jobService.download(jobService.queryAll(criteria!!), response)
    }

    @Log("查询岗位")
    @Schema(description = "查询岗位")
    @GetMapping
    @PreAuthorize("@el.check('job:list','user:list')")
    fun getJobs(
        criteria: JobQueryCriteria,
        pageable: Pageable?
    ): ResponseEntity<*> {
        // 数据权限
        return ResponseEntity(jobService.queryAll(criteria, pageable), HttpStatus.OK)
    }

    @Log("新增岗位")
    @Schema(description = "新增岗位")
    @PostMapping
    @PreAuthorize("@el.check('job:add')")
    fun create(@Validated @RequestBody resources: Job): ResponseEntity<*> {
        if (resources.id != null) {
            throw BadRequestException("A new " + ENTITY_NAME + " cannot already have an ID")
        }
        return ResponseEntity(jobService.create(resources), HttpStatus.CREATED)
    }

    @Log("修改岗位")
    @Schema(description = "修改岗位")
    @PutMapping
    @PreAuthorize("@el.check('job:edit')")
    fun update(
        @Validated(
            Job.Update::class
        ) @RequestBody resources: Job?
    ): ResponseEntity<*> {
        jobService.update(resources!!)
        return ResponseEntity<Any?>(HttpStatus.NO_CONTENT)
    }

    @Log("删除岗位")
    @Schema(description = "删除岗位")
    @DeleteMapping(value = ["/{id}"])
    @PreAuthorize("@el.check('job:del')")
    fun delete(@PathVariable id: Long?): ResponseEntity<*> {
        try {
            jobService.delete(id!!)
        } catch (e: Throwable) {
            ThrowableUtil.throwForeignKeyException(e, "该岗位存在用户关联，请取消关联后再试")
        }
        return ResponseEntity<Any?>(HttpStatus.OK)
    }

    companion object {
        private const val ENTITY_NAME = "job"
    }
}